<template>
	<view class="container">

		<!-- 支付倒计时 建议补充进去 -->

		<!-- 仅有ams 0008下的门店编码0021才有微信支付 -->
		<view class="content-box" v-if="orgCode == '0021'">
			<view class="title">
				支付方式
			</view>
			<view class="news-continar">
				<view class="flex-center vip-box" v-for="(item,index) in tabsList" :key="index"
					@click="selectTab(item,index)" :class="{ 'active': item.type == currentTab }">
					<view class="" style="display: flex;align-items: center;">
						<image :src="item.img" mode=""></image>
						<view class="text">
							{{item.title}}
						</view>
						<view class="sub-text">
							
						</view>
					</view>
					<image v-if="item.type == currentTab" class="defut_radio"
						src="https://oss.jtmckj.com/wmp/jfsc/pay/Active_radio.png" alt="" />
					<image v-else class="defut_radio" src="https://oss.jtmckj.com/wmp/jfsc/pay/defut_radio.png"
						alt="" />
				</view>
			</view>
		</view>


		<!-- 临时写死的合并微信与积分的单选支付 -->
		<view class="content-box" v-else>
			<view class="title">
				支付方式
			</view>
			<view class="news-continar">
				<view class="flex-center vip-box" v-for="(item,index) in tabsList" :key="index"
					@click="selectTab(item,index)" :class="{ 'active': item.type === currentTab }">
					<view class="" style="display: flex;align-items: center;">
						<image :src="item.img" mode=""></image>
						<view class="text">
							{{item.title}}
						</view>
						<view class="sub-text"  v-if="item.type == '1'">
							<!-- item.num -->
							<!-- (可用{{jfModal.kyNum}}积分)  -->
						</view>
					</view>
					<image v-if="item.type === currentTab" class="defut_radio"
						src="https://oss.jtmckj.com/wmp/jfsc/pay/Active_radio.png" alt="" />
					<image v-else class="defut_radio" src="https://oss.jtmckj.com/wmp/jfsc/pay/defut_radio.png"
						alt="" />
				</view>
			</view>
		</view>


		<!-- 动态组合的支付 -->
		<!-- <view class="content-box">
			<view class="title">
				积分抵扣
			</view>
			<view class="news-continar" style="margin-bottom: 0rpx;">
				<view class="flex-center vip-box">
					<view class="" style="display: flex;align-items: center;">
						<image src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/jfsc/pay/jf-img.png" mode=""></image>
						<view class="text">
							积分抵扣
						</view>
						<view class="sub-text">
							(可用{{jfModal.kyNum}}积分)
						</view>
					</view>
					<up-switch activeColor="#FF6A00" v-model="jfValue" @change="jfChange"></up-switch> 
				</view>

				<view class=" vip-box">
					<view class="chxy-row-bt"> 
						<view> 使用 </view>
						<view class="chxy-row-bt" style="background-color: #F2F2F2;width: 586rpx;height: 80rpx;border-radius: 8rpx;">
							<up-input placeholder="请输入积分" v-model="jfModal.syNum" @change="jfNumChange" border='none' type='number'></up-input>
							<view style="margin-right: 20rpx;color: #212121;">积分</view>
						</view>
					</view> 
					<view class="chxy-row-bt">
						<view></view>
						<view class="chxy-row-ac" style="width: 586rpx;height: 40rpx; margin-top: 20rpx;"> 
							<text style="color: #666666">已抵扣:</text>
							<text style="color: #FF6A00;"> {{jfModal.ydkNum || 0}}元</text>
							<text style="color: #666666">, 待支付:</text>
							<text style="color: #FF6A00;"> {{jfModal.dzfNum || 0}}元</text>
						</view>
					</view> 
				</view> 
			</view>
			
			<view class="h-20"></view>
			<view style="color: #666666;line-height: 36rpx;font-size: 24rpx;">
				<view>本次最高可用积分：0</view>
				<view>账户剩余积分：0</view>
				<view>1积分=1元</view>
			</view> 
			
		</view> -->

		<!-- 底部支付按钮区域 -->
		<view class="pay-continar ">
			<view class="pay-bewtten flex-center-bewtten">
				<view class="jf-all-price">
					<text>{{orderInfo.exchangeScore || 0}}积分</text>
					<text>+{{orderInfo.exchangeMoney || 0}}元</text>
				</view>
				<view class="zf-btn" @click="show = true">
					立即支付
				</view>
			</view>
		</view>


		<!-- 弹窗 -->
		<up-popup :show="show" mode="center" :round="10">
			<view class="show-pay-view" >
				<view style="height: 60rpx;"></view>
				<view style="text-align: center;font-weight: bold;font-size: 36rpx;color: #212121;">确认兑换</view>
				<view v-if="currentTab == '3'" style="margin-top: 45rpx;">确认使用 <text
						class="orge-col">{{orderInfo.exchangeMoney || 0}}元</text>兑换
					<text class="orge-col">{{orderInfo.name}}</text> 一张？
				</view>
				<view v-if="currentTab == '1'" style="margin-top: 45rpx;">确认使用 <text
						class="orge-col">{{orderInfo.exchangeScore || 0}}积分</text>兑换
					<text class="orge-col">{{orderInfo.name}}</text> 一张？
				</view>
				<view class="chxy-row-bt" style="margin-top: 60rpx;">
					<view class="close-btn" @click="show = false">取消</view>
					<view v-if="orgCode == '0021' || currentTab == '3'" class="submit-btn" @tap="$u.throttle(prePay, 1000)">确认</view>
					<view v-else class="submit-btn" @tap="$u.throttle(toOrder, 1000)">确认</view>
				</view>
			</view>
		</up-popup>


	</view>
</template>

<script setup>
	import { goodsPublic } from '@/pagesPointShop/api/goods.js';
	import { onLoad, onUnload, onShow, onHide } from '@dcloudio/uni-app';
	import { ref, reactive } from 'vue';
	// import { useUserStore } from '@/store/user.js'; 
	import wx from 'weixin-js-sdk'
	import { HFiveMemberAppObjProcess } from '@/api/public.js'

	// shopInfo下必有： brandCode: "0003"   orgCode : "0015"
	const orgCode = uni.getStorageSync('shopInfo').orgCode

	// const store = useUserStore();
	const jfValue = ref(false)
	const jfNumValue = ref()
	const show = ref(false)

	const orderCode = ref('')
	const orderInfo = ref('')
	const orderModal = ref({})
	const jfModal = ref({
		kyNum: "",
		syNum: '',
		ydkNum: '',
		dzfNum: ''
	})
	let tabsList = reactive([
		// {
		// 	img: 'https://oss.jtmckj.com/wmp/jfsc/pay/vip-icon.png',
		// 	title: '会员卡支付',
		// 	type: '2', //正常接口返回 或者约定类型
		// 	num: '0'
		// },  
		{
			img: 'https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/jfsc/pay/jf-img.png',
			title: '会员卡积分支付',
			type: '1', //正常接口返回 或者约定类型
			num: '0'
		},
		{
			img: 'https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/jfsc/pay/wechat.png',
			title: '微信支付',
			type: '3', //正常接口返回 或者约定类型
			num: '0'
		},
	]);
	const currentTab = ref('1') //支付tab默认选中第一个   
	const selectTab = (item, index) => {
		currentTab.value = item.type
	}

	const jfChange = (e) => {
		console.log("jfChange：", e);
	}

	const toOrder = async () => {
		console.log('orderModal.value：', orderModal.value)
		const { opFlag, content } = await goodsPublic(orderModal.value)
		console.log('orderModal.value：', opFlag)
		console.log('orderModal.value：', content)
		if (opFlag !== '1') {
			// 买单失败
			return
		}
		// console.log('content：',content)
		uni.reLaunch({
			url: '/pagesPointShop/view/score/detail?code=' + content.rowData.orderCode
		})
	}

	// 上一个页面-已创建了订单号
	onLoad((options) => {
		orderCode.value = options.orderCode // 商品订单编码
		orderInfo.value = JSON.parse(decodeURIComponent(options.orderInfo)) //正常查询订单信息 initDetailsData 
		console.log('orderInfo.value1', options.orderCode) // initDetailsData()
		console.log('orderInfo.value2', orderInfo.value) // initDetailsData()
		initJf()
		orderModal.value = {
			"functionName": "mallOrderPay",
			"contentData": {
				"code": orderCode.value, // 订单编码
				"memberCode": uni.getStorageSync('pointUserInfo').memberCode,
				"memberCardCode": uni.getStorageSync('pointUserInfo').code,
				"remark": "",
				"detail": [{
					"payType": "1", // 支付方式: 1积分2会员余额3微信
					"payAmt": orderInfo.value.exchangeScore || 0 // 支付金额/积分
				}]
			}
		}
	});
	
	onShow((options) => {
		// console.log(orderInfo.exchangeMoney  orderInfo.exchangeScore);
		if(orderInfo.value.exchangeMoney <= 0){
			tabsList = [
				{
					img: 'https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/jfsc/pay/jf-img.png',
					title: '会员卡积分支付',
					type: '1', //正常接口返回 或者约定类型
					num: '0'
				},
			]
			currentTab.value = '1'
		}
		if(orderInfo.value.exchangeScore <= 0){
			tabsList = [
				{
					img: 'https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/jfsc/pay/wechat.png',
					title: '微信支付',
					type: '3', //正常接口返回 或者约定类型
					num: '0'
				},
			]
			currentTab.value = '3'
		}
	});

	// 获取用户当前最新积分
	const initJf = () => {
		let modal = {
			"functionName": "getMemberInfo",
			"contentData": {
				"memberCode": uni.getStorageSync('pointUserInfo').memberCode,
				"memberCardCode": uni.getStorageSync('pointUserInfo').code,
			}
		}
		goodsPublic(modal).then(res => {
			if (res.opFlag !== '1') { return }
			let result = res.content.rowData
			let userModal = result.find(item => item.cardType == 2)
			// console.log('userModal：', userModal); 
			// store.SetUserInfo(userModal || '') 
			uni.setStorageSync('pointUserInfo', userModal)
			jfModal.value.kyNum = userModal.currentPoint || 0
		})
	};

	// 查询订单信息 - 目前没有接口
	const initDetailsData = () => {
		// let moda = { }
		// goodsPublic(modal)
		// if (opFlag !== '1') {  
		// 	return  
		// } 
	}

	// 预支付 - initDetailsPay
	const prePay = async () => {
		// 通过订单号 查询微信支付的支付参数 
		// console.log('prePay1:',orderCode.value);
		// console.log('prePay2:',orderInfo.value); 
		if (orderInfo.value.exchangeMoney <= 0) {
			uni.showToast({
				title: '支付金额有误',
				icon: 'none'
			})
			return
		}
		uni.showLoading({
			title: '',
			mask: true
		});
		let modalPayParam = {
			"functionName": "mallWXOrderPay",
			"contentData": {
				"code": orderCode.value, // 订单编码
				"memberCode": uni.getStorageSync('pointUserInfo').memberCode,
				"memberCardCode": uni.getStorageSync('pointUserInfo').code,
				"remark": "",
				"detail": [{
					"payType": "3", // 支付方式: 1积分2会员余额3微信
					"payAmt": orderInfo.value.exchangeMoney || 0 // 支付金额/积分
				}]
			}
		}
		const { opFlag, content } = await goodsPublic(modalPayParam)
		console.log('orderModal.value：', opFlag)
		console.log('orderModal.value：', content)
		if (opFlag !== '1') {
			uni.hideLoading();
			uni.showToast({
				title: '预支付失败',
				icon: 'none'
			})
			return
		}
		uni.hideLoading();
		const resultPay = content.rowData
		// console.log('resultPay：', resultPay)
		show.value = false
		toPayWx(resultPay, orderCode.value)
	}

	// 唤起微信支付
	const toPayWx = (opt, resultOrder) => {
		wx.config({
			debug: false, // 这里一般在测试阶段先用true，等打包给后台的时候就改回false,
			appId: opt.appId, // 必填，公众号的唯一标识
			timestamp: opt.timeStamp, // 必填，生成签名的时间戳
			nonceStr: opt.nonceStr, // 必填，生成签名的随机串
			signature: opt.paySign, // 必填，签名
			jsApiList: ["chooseWXPay"] // 必填，需要使用的JS接口列表 
		});
		wx.ready(() => {
			wx.chooseWXPay({
				appId: opt.appId, // 必填，公众号的唯一标识
				timestamp: opt.timeStamp, // 必填，生成签名的时间戳
				nonceStr: opt.nonceStr, // 必填，生成签名的随机串
				package: opt.package, // 统一支付接口返回的prepay_id参数值，提交格式如:prepay_id=|*|*|*)
				signType: opt.signType, // 签名方式，根据后端返回就行，一般默认为'SHA1'，使用新版支付需传入'MD5'
				paySign: opt.paySign, // 必填，支付签名
				success: function(payRes) {
					// 支付成功后的回调函数 
					uni.showToast({
						title: '微信支付成功',
						icon: 'none'
					})
					setTimeout(function() {
						uni.reLaunch({
							url: '/pagesPointShop/view/score/detail?code=' +
								resultOrder
						})
					}, 800);
				},
				cancel: function(payRes) {
					console.log('cancel取消支付：', payRes)
					uni.showToast({
						title: '取消微信支付',
						icon: 'none'
					})
					// wxPayCancel(payRes, opt, resultOrder)
				},
				fail: function(payRes) {
					uni.showToast({
						title: '微信支付失败',
						icon: 'none'
					})
					// wxPayFail(payRes, opt, resultOrder) 
				}
			});
		});
	}

	// 支付失败 - 取消特定业务 - 正常后端自行处理
	const wxPayFail = (payRes, opt, resultOrder) => {
		console.log(payRes, opt, resultOrder);
		let modalFail = {
			"functionName": "MenberCodePayQuery_H5",
			"contentData": {
				"OutTradeNo": opt.tradeNo,
				"PayType": '1'
			}
		}
		HFiveMemberAppObjProcess(modalFail).then(res => {
			// uni.reLaunch({
			// 	url: `/pages/order/index` // 跳转到订单详情
			// })
		}).catch(err => {
			// 取消订单
			let modalCancel = {
				"functionName": "MemberOrderCancel_H5",
				"contentData": {
					"orderBatchCode": resultOrder.orderBatchCode,
					"tradeNo": opt.tradeNo
				}
			}
			if (canCancle.value == '1') {
				HFiveMemberAppObjProcess(modalCancel).then(res => {
					uni.showToast({
						title: '已取消支付',
						icon: 'none'
					})
					// uni.navigateBack()
				})
			} else {
				// uni.navigateBack()
			}

		})
	}

	// 取消支付 - 取消特定业务 - 正常后端自行处理
	const wxPayCancel = (payRes, opt, resultOrder) => {
		// 取消订单
		let modalCancel = {
			"functionName": "MemberOrderCancel_H5",
			"contentData": {
				"orderBatchCode": resultOrder.orderBatchCode,
				"tradeNo": opt.tradeNo
			}
		}
		if (canCancle.value == '1') {
			HFiveMemberAppObjProcess(modalCancel).then(res => {
				uni.showToast({
					title: '已取消支付',
					icon: 'none'
				})
				// uni.navigateBack()
			})
		} else {
			// uni.navigateBack()
		}

	}
</script>

<style scoped lang="less">
	.flex {
		display: flex;
	}

	.flex-center {
		display: flex;
		align-items: center;
	}

	.jf-border {
		border-bottom: 1rpx solid #E6E6E6;
		padding-bottom: 29rpx;
	}

	.flex-center-bewtten {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.container {
		width: 100%;
		height: 100vh;
		background-color: #f2f2f2;

		.content-box {
			padding: 40rpx 24rpx 0 24rpx;

			.title {
				font-weight: bold;
				font-size: 32rpx;
				color: #212121;
				margin-bottom: 24rpx;
			}

			.news-continar {
				padding: 30rpx 24rpx 0 24rpx;
				background: #FFFFFF;
				border-radius: 16rpx;
				margin-bottom: 10rpx;

				.vip-box {
					padding-bottom: 29rpx;
					margin-bottom: 30rpx;
					justify-content: space-between;
					border-bottom: 1rpx solid #E6E6E6;

					&:nth-last-child(1) {
						border: none;
						margin-bottom: 0rpx;
					}

					image {
						width: 60rpx;
						height: 60rpx;
					}

					.text {
						margin-left: 24rpx;
						font-weight: 500;
						font-size: 32rpx;
						color: #212121;
					}

					.defut_radio {
						width: 32rpx;
						height: 32rpx;
					}
				}
			}
		}

		.jf-continar {
			padding: 30rpx 24rpx 18rpx 24rpx;
			background: #FFFFFF;
			border-radius: 16rpx;

			.jf-img {
				width: 60rpx;
				height: 60rpx;
				margin-right: 24rpx;
			}

			.jf-title {
				font-weight: 500;
				font-size: 32rpx;
				color: #212121;

				.jf-fb {
					margin-left: 16rpx;
					font-weight: 500;
					font-size: 24rpx;
					color: #666666;
				}
			}

			.sy-continar {
				margin-top: 20rpx;

				.sy-title {
					font-weight: 500;
					font-size: 28rpx;
					color: #666666;
				}

				.jf-content-box {
					width: 586rpx;
					height: 80rpx;
					background: #F2F2F2;
					border-radius: 8rpx;
				}
			}
		}

		.dk-continar {
			margin-top: 20rpx;
			padding-left: 68rpx;

			.dk-box {
				font-weight: 500;
				font-size: 24rpx;
				color: #666666;

				text {
					color: #FF6A00;
				}
			}
		}

		.jf-footer-content {
			margin-top: 23rpx;

			.info {
				font-weight: 500;
				font-size: 24rpx;
				color: #666666;
			}
		}
	}

	.pay-continar {

		position: fixed;
		bottom: 0rpx;
		width: 100%;
		background: #FFFFFF;
		border-radius: 24rpx 24rpx 0rpx 0rpx;

		.pay-bewtten {
			padding: 20rpx 24rpx;

			.jf-all-price {
				font-size: 32rpx;
				color: #212121;
			}

			.zf-btn {
				width: 240rpx;
				height: 80rpx;
				background: #FF6A00;
				border-radius: 40rpx;
				text-align: center;
				line-height: 80rpx;
				font-size: 32rpx;
				color: #FFFFFF;
			}
		}

	}

	::v-deep .u-input {
		margin-left: 16rpx;
		background: #F2F2F2;
	}

	.sub-text {
		font-size: 24rpx;
		color: #666666;
		width: 300rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		margin-left: 12rpx;
	}

	.submit-btn {
		width: 240rpx;
		height: 80rpx;
		background: #FF6A00;
		border-radius: 40rpx;
		text-align: center;
		line-height: 80rpx;
		font-weight: 500;
		font-size: 36rpx;
		color: #fff;
	}

	.close-btn {
		width: 236rpx;
		height: 76rpx;
		border-radius: 40rpx;
		border: 2rpx solid #999999;
		text-align: center;
		line-height: 80rpx;
		font-weight: 500;
		font-size: 36rpx;
		color: #999999;
	}

	.but-bottom-view {
		width: 100vw;
		height: 120rpx;
		position: fixed;
		background-color: #F2F2F2;
		bottom: 0;
		left: 0;

		.but-bottom-fixed {
			width: 702rpx;
			height: 80rpx;
			background: #FF6A00;
			border-radius: 40rpx;
			font-family: PingFang SC;
			font-weight: bold;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 30rpx;
			margin: 0 24rpx;
		}
	}
	
	.show-pay-view{
		width: 500rpx;  background: #FFFFFF; border-radius: 16rpx;padding:0 50rpx 40rpx 50rpx ;
		.orge-col{
			
		}
	}
	
	
</style>